﻿#ifndef DTUTABLEMODEL_H
#define DTUTABLEMODEL_H

#include <QtWidgets>
#include <QWidget>
#include "../../include/dtudata.h"

class DTUTableModel : public QAbstractTableModel
{
    Q_OBJECT
public:
    DTUTableModel();
    ~DTUTableModel();

    void setHorizontalHeader(const QStringList &headers);
    void setList(const QList<DTUData>&);
    void updateCurrent(uint id, const QList<int>& data);

    bool addDevice(const DTUData& data);
    bool deleteDevice(const QModelIndex& index);

    uint getDeviceId(const QModelIndex& index) const;
    const DTUData& getDeviceData(const QModelIndex& index) const;
    const DTUData& getDeviceData(int row) const { return m_list[row];}
    DTUData getDeviceData(const QModelIndex& index) {return  m_list[index.row()];}

    void setDeviceData(const QModelIndex& index, const DTUData& data);
    DTUData& lastDevice() {return  m_list.back();}

    int size() const {return m_list.size();}

    uint ip2id(int ip)
    {
        auto it = m_list.begin();
        for(;it!=m_list.end();it++)
            if(it->ip == ip)
                return it->id;
        return 0;
    }
protected:
    //read-onlys
    virtual Qt::ItemFlags flags(const QModelIndex &index) const override;
    virtual QVariant data(const QModelIndex &index, int role) const override;
    virtual QVariant headerData(int section, Qt::Orientation orientation, int role) const override;
    virtual int rowCount(const QModelIndex &parent = QModelIndex()) const override;
    virtual int columnCount(const QModelIndex &parent = QModelIndex()) const override;

    //editable items
    virtual bool setData(const QModelIndex &index, const QVariant &value, int role) override;

    //resizable models
    virtual bool insertRows(int row, int count, const QModelIndex &parent = QModelIndex()) override;
    virtual bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()) override;

private:
    QStringList m_horizontalHeader;
    QList<DTUData> m_list;
};

#endif // DTUTABLEMODEL_H
